# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
from django.views.generic.list_detail import object_list, object_detail
from django.views.generic.create_update import create_object, delete_object, \
    update_object
from google.appengine.ext import db
from mimetypes import guess_type
from photo.models import Category, Album, Photo
from ragendja.dbutils import get_object_or_404, get_object
from ragendja.template import render_to_response
from photo import utils

def main(request):
     return render_to_response(request, 'photo/main.html')

def create_admin_user(request):
    user = User.get_by_key_name('admin')
    if not user or user.username != 'admin' or not (user.is_active and
            user.is_staff and user.is_superuser and
            user.check_password('admin')):
        user = User(key_name='admin', username='admin',
            email='admin@localhost', first_name='Boss', last_name='Admin',
            is_active=True, is_staff=True, is_superuser=True)
        user.set_password('admin')
        user.put()
    return render_to_response(request, 'photo/admin_created.html')

def category_list(request, path=None):
    kwargs = {}
    if not path or not len(path):
        kwargs['categories'] = Category.all().filter('parent_ref = ', None)
        return render_to_response(request, 'photo/category_list.html', kwargs)
            
    if len(path) and path[-1] == '/':
        path = path[:-1]
    slug = path.split('/')[-1]
    if not slug or not len(slug):
        raise Http404('incorrect url')
    slug = slug.lstrip()
    root_category = Category.all().filter('slug = ', slug).get()        
    if root_category:
        categories = root_category.children
        kwargs['parent'] = root_category
        if categories:
            kwargs['categories'] = Category.all().filter('parent_ref = ', root_category)
            return render_to_response(request, 'photo/category_list.html', kwargs)
        kwargs['albums'] = root_category.albums
        return render_to_response(request, 'photo/album_list.html', kwargs)
    
    album = Album.all().filter('slug = ', slug).get()
    if album:
        kwargs['album'] = album
        kwargs['photos'] = album.photos        
        return render_to_response(request, 'photo/album_view.html', kwargs)
    
    photo = Photo.all().filter('slug = ', slug).get()
    if photo:
        kwargs['photo'] = photo
        return render_to_response(request, 'photo/photo_view.html', kwargs)
            
    raise Http404('Could not find any photo or category with name ' + slug)

def picasa_sync(request):
    albums_created, photos_created = utils.picasa_sync('p.drobushevich@gmail.com')
    return HttpResponse('Sync finished, created %s albums and %s photos' % (albums_created, photos_created))
    